package com.neusoft.bizcore.license.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.neusoft.bizcore.license.bean.LicenseCreateBean;
import com.neusoft.bizcore.license.service.LicenseVerifyService;

@Controller
@RequestMapping("/licenses")
public class LicenseController {

    @Autowired
    private LicenseVerifyService licenseVerifyService;

    @GetMapping
    public String index(@ModelAttribute LicenseCreateBean licenseCreateBean) {
        return "licenses/form";
    }

    @PostMapping
    public ModelAndView create(@Valid LicenseCreateBean licenseCreateBean, BindingResult result,
            RedirectAttributes redirect, HttpServletRequest request, HttpServletResponse response) {

        final ModelAndView mav = new ModelAndView();

        if (result.hasErrors()) {
            mav.setViewName("licenses/form");
            mav.addObject("formErrors", result.getAllErrors());
            mav.addObject("licenseCreateBean", licenseCreateBean);
            return mav;
        }

        final File license = this.licenseVerifyService.create(licenseCreateBean);
        mav.setViewName("licenses/form");
        mav.addObject("licenseCreateBean", new LicenseCreateBean());
        mav.addObject("licPath", Base64.getEncoder().encodeToString(license.getAbsolutePath().getBytes()));
        return mav;
    }

    @GetMapping("/download/{licPath}")
    public ResponseEntity<byte[]> export(@PathVariable String licPath) throws IOException {

        final HttpHeaders headers = new HttpHeaders();
        final InputStream fis = new FileInputStream(new File(new String(Base64.getDecoder().decode(licPath))));
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        int len;
        final byte[] buffer = new byte[1024];
        while ((len = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        final byte[] bytes = baos.toByteArray();
        fis.close();
        baos.close();

        headers.setContentDispositionFormData("attachment", "license.lic");

        return new ResponseEntity<>(bytes, headers, HttpStatus.CREATED);
    }

}
